package com.ydt.dockingclients.config;

import cn.hutool.extra.spring.SpringUtil;
import com.ydt.dockingclients.auth.SdkYdtAuthTokenService;
import com.ydt.dockingclients.utils.YdtClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class YdtTokenManage {
    private static final AtomicReference<YdtToken> tokenRef = new AtomicReference<>();

    @Data
    static class YdtToken {
        private String token;
        private long expireTime;

        public YdtToken(String token, long expireTime) {
            this.token = token;
            this.expireTime = expireTime;
        }
    }

    private YdtTokenManage() {
        // 私有构造函数防止实例化
    }

    public static String getToken() {
        YdtToken tokenObj = tokenRef.get();
        if (tokenObj == null) {
            tokenObj = fetchTokenFromExternalSource();
            // 只有在成功获取token后才设置到AtomicReference中
            tokenRef.compareAndSet(null, tokenObj);
        }
        long thisTime = System.currentTimeMillis();
        if (thisTime > tokenObj.expireTime) {
            log.info("token expired, token:{}", tokenObj.token);
            tokenObj = fetchTokenFromExternalSource();
            tokenRef.compareAndSet(null, tokenObj);
        }
        return tokenObj.getToken();
    }

    /**
     * 刷新Token
     * @return
     */
    public static String refreshToken(){
        YdtToken tokenObj = fetchTokenFromExternalSource();
        tokenRef.compareAndSet(null, tokenObj);
        return tokenObj.getToken();
    }

    private static YdtToken fetchTokenFromExternalSource() {
        try {
            long expire = 1000 * 60 * 60 * 12;
            return new YdtToken(YdtClient.authToken(), System.currentTimeMillis() + expire);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
